package jopo;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.UnsupportedEncodingException;
import java.util.Random;

public class ValidateCode {
    // 图片的宽度。
    private int width = 120;
    // 图片的高度。
    private int height = 40;
    // 验证码
    private String code = "";
    // 验证码图片Buffer
    private BufferedImage buffImg;

    public String getCode() {
        return code;
    }

    public BufferedImage getBuffImg() {
        return buffImg;
    }

    public ValidateCode() throws UnsupportedEncodingException {
        //创建绘图buffer
        buffImg = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
        //创建绘图工具
        Graphics graphics = buffImg.getGraphics();
        //设置背景色
        graphics.setColor(new Color(255,255,255));
        //填充
        graphics.fillRect(0,0,width,height);
        for(int i=0;i<4;i++) {
            String character;
            int hightPos, lowPos; // 定义高低位
            Random random = new Random();
            hightPos = (176 + Math.abs(random.nextInt(39))); //获取高位值
            lowPos = (161 + Math.abs(random.nextInt(93))); //获取低位值
            byte[] b = new byte[2];
            b[0] = (new Integer(hightPos).byteValue());
            b[1] = (new Integer(lowPos).byteValue());
            //转中文
            character = new String(b, "GBk");
            //随机生成验证码颜色
            graphics.setColor(new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255)));
            //随机定位验证码
            graphics.drawString(character, (i * 30) + 15, 20 + random.nextInt(10));

            code+=character;
        }
        graphics.drawLine(5,20,115,20);
    }
}
